<template>
  <view class="membership-page">
    <!-- 加载中提示 -->
    <view class="loading-container" v-if="isLoading">
      <view class="loading-spinner"></view>
      <text class="loading-text">加载中...</text>
    </view>
    
    <block v-else>
      <!-- 顶部会员信息卡片 -->
      <view class="membership-card">
        <view class="membership-header">
          <view class="user-info">
            <image class="avatar" :src="userInfo.avatarUrl || 'http://101.200.154.121:19000/teacher-manage-static/static/tabbar/logo.png'"></image>
            <view class="user-details">
              <view class="nickname">{{ userInfo.nickname || '用户' }}</view>
              <view class="member-tag">{{ getMembershipType(userInfo.hy) }}</view>
            </view>
          </view>
        </view>
        <view class="membership-details">
          <view class="detail-item">
            <view class="label">会员类型</view>
            <view class="value">{{ getMembershipType(userInfo.hy) }}</view>
          </view>
          <view class="detail-item">
            <view class="label">开通时间</view>
            <view class="value">{{ formatDate(userInfo.hySj) }}</view>
          </view>
          <view class="detail-item">
            <view class="label">到期时间</view>
            <view class="value">{{ formatDate(userInfo.hyDq) }}</view>
          </view>
          <view class="detail-item" v-if="userInfo.hy">
            <view class="label">会员状态</view>
            <view class="value status">{{ isExpired ? '已过期' : '生效中' }}</view>
          </view>
          <!-- 添加提示信息，引导普通用户充值 -->
          <view class="upgrade-tip" v-if="userInfo.hy === 0">
            <text>点击充值开通会员</text>
            <uni-icons type="arrowright" size="16" color="#FFB800"></uni-icons>
          </view>
        </view>
      </view>
      
      <!-- 会员权益 -->
      <view class="membership-benefits">
        <view class="section-title">会员权益</view>
        <view class="benefits-list">
          <view class="benefit-item">
            <uni-icons type="checkmarkempty" size="20" color="#FFB800"></uni-icons>
            <text>联系老师畅聊无限制</text>
          </view>
          <view class="benefit-item">
            <uni-icons type="checkmarkempty" size="20" color="#FFB800"></uni-icons>
            <text>收藏课程无限量</text>
          </view>
          <view class="benefit-item">
            <uni-icons type="checkmarkempty" size="20" color="#FFB800"></uni-icons>
            <text>专享学习社区</text>
          </view>
          <view class="benefit-item">
            <uni-icons type="checkmarkempty" size="20" color="#FFB800"></uni-icons>
            <text>每月学习资料包</text>
          </view>
        </view>
      </view>
      
      <!-- 会员套餐 -->
      <view class="membership-packages" v-if="!userInfo.hy || isExpired">
        <view class="section-title">开通会员</view>
        <view class="packages-list">
          <view class="package-item" v-for="(item, index) in packages" :key="index" 
                :class="{'selected': selectedPackage && selectedPackage.id === item.id}"
                @click="selectPackage(item)">
            <view class="package-info">
              <view class="package-name">{{ item.name }}</view>
              <view class="package-duration">{{ item.duration }}</view>
            </view>
            <view class="package-price">
              <text class="currency">¥</text>
              <text class="amount">{{ item.price }}</text>
            </view>
          </view>
        </view>
      </view>
      
      <!-- 续费按钮 -->
      <view class="renew-button" v-if="userInfo.hy && !isExpired">
        <button type="primary" @click="goToMemberIndex">续费会员</button>
      </view>
      
      <!-- 底部按钮 -->
      <view class="bottom-button" v-if="!userInfo.hy || isExpired">
        <button type="primary" @click="goToMemberIndex()" :disabled="false">{{ userInfo.hy ? '续费会员' : '开通会员' }}</button>
      </view>
    </block>
  </view>
</template>

<script>
export default {
  data() {
    return {
      userInfo: {},
      isExpired: false,
      isLoading: true,
      selectedPackage: null,
      showPackages: false,
      packages: [
        { id: 0, name: '月度会员', duration: '30天', price: 39, type: 0 },
        { id: 1, name: '季度会员', duration: '90天', price: 79, type: 1 },
        { id: 2, name: '年度会员', duration: '365天', price: 299, type: 2 }
      ]
    }
  },
  onLoad() {
    this.getUserInfo();
  },
  methods: {
    getUserInfo() {
      try {
        this.isLoading = true;
        
        // 从本地存储获取用户信息
        const userInfo = uni.getStorageSync('userInfo');
        
        if (userInfo) {
          // 直接使用用户信息对象，不需要JSON.parse
          this.userInfo = typeof userInfo === 'string' ? JSON.parse(userInfo) : userInfo;
          
          console.log('用户会员信息:', this.userInfo);
          
          // 检查会员是否过期
          if (this.userInfo.hyDq) {
            const now = new Date();
            const expireDate = new Date(this.userInfo.hyDq);
            this.isExpired = now > expireDate;
          }
          
          // 从服务器获取最新的用户信息
          this.fetchLatestUserInfo(this.userInfo.id);
        } else {
          // 未登录，跳转到登录页
          this.isLoading = false;
          uni.navigateTo({
            url: '/pages/login/login'
          });
        }
      } catch (error) {
        this.isLoading = false;
        console.error('获取用户信息失败:', error);
        uni.showToast({
          title: '获取用户信息失败',
          icon: 'none'
        });
      }
    },
    
    // 从服务器获取最新的用户信息
    async fetchLatestUserInfo(userId) {
      try {
        const res = await new Promise((resolve, reject) => {
          uni.request({
            url: `http://203.34.152.33/user/user/info/${userId}`,
            method: 'GET',
            header: {
              'Authorization': uni.getStorageSync('access_token')
            },
            success: (response) => {
              resolve(response)
            },
            fail: (error) => {
              reject(error)
            }
          })
        });

        console.log('获取用户信息结果:', res);

        if (res.statusCode === 200 && res.data.code === 200) {
          console.log('用户详细信息:', res.data.data);
          
          // 调试所有可能的会员日期字段
          console.log('可能的会员日期字段:',
            '- hySj:', res.data.data.hySj,
            '- hy_sj:', res.data.data.hy_sj,
            '- hySJ:', res.data.data.hySJ,
            '- hyDq:', res.data.data.hyDq, 
            '- hy_dq:', res.data.data.hy_dq,
            '- hyDQ:', res.data.data.hyDQ
          );
          
          // 更新用户信息
          const userData = {
            id: res.data.data.id,
            nickname: res.data.data.nickname || '',
            phone: res.data.data.phone || '',
            avatarUrl: res.data.data.avatarUrl || '/static/default-avatar.png',
            role: res.data.data.role || '',
            status: res.data.data.status || '',
            hy: res.data.data.hy || 0,
            hySj: res.data.data.hySj || res.data.data.hy_sj || res.data.data.hySJ || '',
            hyDq: res.data.data.hyDq || res.data.data.hy_dq || res.data.data.hyDQ || ''
          };
          
          console.log('会员开通时间:', userData.hySj);
          console.log('会员到期时间:', userData.hyDq);
          
          this.userInfo = userData;
          
          // 更新本地存储
          uni.setStorageSync('userInfo', userData);
          
          // 检查会员是否过期
          if (this.userInfo.hyDq) {
            const now = new Date();
            const expireDate = new Date(this.userInfo.hyDq);
            this.isExpired = now > expireDate;
          }
        } else {
          uni.showToast({
            title: '获取用户信息失败',
            icon: 'none'
          });
        }
      } catch (error) {
        console.error('获取最新用户信息失败:', error);
        uni.showToast({
          title: '获取用户信息失败',
          icon: 'none'
        });
      } finally {
        this.isLoading = false;
      }
    },
    getMembershipType(type) {
      switch (type) {
        case 0:
          return '普通用户';
        case 1:
          return 'VIP会员';
        case 2:
          return 'SVIP会员';
        default:
          return '普通用户';
      }
    },
    selectPackage(packageItem) {
      this.selectedPackage = packageItem;
      this.packages.forEach(p => {
        p.selected = p.id === packageItem.id;
      });
    },
    async goToPayment() {
      if (!this.selectedPackage) {
        uni.showToast({
          title: '请选择会员套餐',
          icon: 'none'
        });
        return;
      }
      
      const userId = this.userInfo.id;
      this.isLoading = true;
      
      try {
        const res = await new Promise((resolve, reject) => {
          uni.request({
            url: 'http://203.34.152.33/user/api/membership/create',
            method: 'POST',
            header: {
              'Authorization': uni.getStorageSync('access_token'),
              'Content-Type': 'application/json'
            },
            data: {
              userId: userId,
              type: this.selectedPackage.type,
              amount: this.selectedPackage.price
            },
            success: (response) => {
              resolve(response);
            },
            fail: (error) => {
              reject(error);
            }
          });
        });
        
        console.log('创建订单结果:', res);
        
        if (res.data.code === 200) {
          const orderNo = res.data.data.id;
          
          // 跳转到支付页面
          uni.navigateTo({
            url: `/pages/payment/payment?orderNo=${orderNo}&amount=${this.selectedPackage.price}&membershipType=${this.selectedPackage.type}`
          });
        } else {
          uni.showToast({
            title: res.data.message || '创建订单失败',
            icon: 'none'
          });
        }
      } catch (error) {
        console.error('创建订单失败:', error);
        uni.showToast({
          title: '网络错误，请稍后重试',
          icon: 'none'
        });
      } finally {
        this.isLoading = false;
      }
    },
    formatDate(dateString) {
      if (!dateString) return '尚未开通';
      const date = new Date(dateString);
      if (isNaN(date.getTime())) return dateString;
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
    },
    goToMemberIndex() {
      uni.navigateTo({
        url: '/pages/member/index'
      });
    }
  }
}
</script>

<style>
.membership-page {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding: 20rpx;
}

.membership-card {
  background-color: #ffffff;
  border-radius: 12rpx;
  padding: 30rpx;
  margin-bottom: 30rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

/* 普通用户卡片添加点击效果 */
.membership-card:active {
  opacity: 0.8;
}

.membership-header {
  margin-bottom: 30rpx;
}

.user-info {
  display: flex;
  align-items: center;
}

.avatar {
  width: 120rpx;
  height: 120rpx;
  border-radius: 60rpx;
  margin-right: 20rpx;
}

.nickname {
  font-size: 36rpx;
  font-weight: bold;
  margin-bottom: 10rpx;
}

.member-tag {
  display: inline-block;
  background-color: #FFB800;
  color: #ffffff;
  font-size: 24rpx;
  padding: 6rpx 16rpx;
  border-radius: 20rpx;
}

.membership-details {
  margin-top: 30rpx;
  border-top: 1px solid #f0f0f0;
  padding-top: 30rpx;
}

.detail-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20rpx;
}

.label {
  color: #666;
  font-size: 28rpx;
}

.value {
  font-size: 28rpx;
  font-weight: bold;
}

.status {
  color: #FFB800;
}

/* 添加引导提示样式 */
.upgrade-tip {
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #FFF9E6;
  padding: 16rpx;
  border-radius: 8rpx;
  margin-top: 20rpx;
  color: #FFB800;
}

.upgrade-tip text {
  margin-right: 10rpx;
  font-size: 28rpx;
}

.membership-benefits, .membership-packages {
  background-color: #ffffff;
  border-radius: 12rpx;
  padding: 30rpx;
  margin-bottom: 30rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  margin-bottom: 20rpx;
}

.benefits-list {
  padding: 10rpx 0;
}

.benefit-item {
  display: flex;
  align-items: center;
  margin-bottom: 20rpx;
}

.benefit-item text {
  margin-left: 10rpx;
  font-size: 28rpx;
}

.packages-list {
  padding: 10rpx 0;
}

.package-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  margin-bottom: 20rpx;
  border-radius: 8rpx;
  background-color: #f9f9f9;
  border: 1px solid #eee;
}

.package-item.selected {
  border-color: #FFB800;
  background-color: #FFF9E6;
}

.package-name {
  font-size: 32rpx;
  font-weight: bold;
  margin-bottom: 10rpx;
}

.package-duration {
  font-size: 24rpx;
  color: #666;
}

.package-price {
  display: flex;
  align-items: baseline;
}

.currency {
  font-size: 24rpx;
  margin-right: 4rpx;
}

.amount {
  font-size: 40rpx;
  font-weight: bold;
  color: #FFB800;
}

.bottom-button, .renew-button {
  padding: 40rpx 30rpx;
}

button[type="primary"] {
  background-color: #FFB800;
  color: #ffffff;
  font-weight: bold;
}

button[disabled] {
  background-color: #cccccc !important;
  color: #ffffff !important;
}

.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40rpx;
}

.loading-spinner {
  width: 60rpx;
  height: 60rpx;
  border: 6rpx solid #f3f3f3;
  border-top: 6rpx solid #FFB800;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 20rpx;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.loading-text {
  color: #666;
  font-size: 28rpx;
}
</style> 
